<template>
  <div class="kv-manager">
    <!-- 操作工具栏 -->
    <el-card class="toolbar-card" shadow="never">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-input
            v-model="searchTerm"
            placeholder="搜索Key或Value..."
            style="width: 300px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select
            v-model="filterOptions.sortBy"
            placeholder="排序字段"
            style="width: 120px; margin-left: 10px"
            @change="handleSortChange"
          >
            <el-option label="Key" value="key" />
            <el-option label="ID" value="id" />
            <el-option label="访问次数" value="accessCount" />
            <el-option label="创建时间" value="createdAt" />
          </el-select>
          
          <el-select
            v-model="filterOptions.sortOrder"
            style="width: 100px; margin-left: 10px"
            @change="handleSortChange"
          >
            <el-option label="升序" value="asc" />
            <el-option label="降序" value="desc" />
          </el-select>
        </div>
        
        <div class="toolbar-right">
          <el-checkbox 
            v-model="filterOptions.showOnlyExisted" 
            @change="handleFilterChange"
          >
            仅显示已存在
          </el-checkbox>
          
          <el-button type="success" @click="showQueryDialog">
            <el-icon><Search /></el-icon>
            高级查询
          </el-button>
          
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            新建KV
          </el-button>
          
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- KV数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="filteredKvPairs"
        style="width: 100%"
        v-loading="tableLoading"
        :default-sort="{ prop: filterOptions.sortBy, order: filterOptions.sortOrder === 'asc' ? 'ascending' : 'descending' }"
      >
        <el-table-column prop="key" label="Key" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ row.key }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="id" label="ID" width="120" sortable>
          <template #default="{ row }">
            <el-tag type="primary" size="small">{{ row.id }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="value" label="Value" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.value">{{ row.value }}</span>
            <el-tag v-else type="info" size="small">NULL</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="existed" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.existed ? 'success' : 'warning'" size="small">
              {{ row.existed ? '已存在' : '新建' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="accessCount" label="访问次数" width="100" sortable>
          <template #default="{ row }">
            {{ row.accessCount || 0 }}
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="editKv(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteKv(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="kvPairCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingKv ? '编辑KV对' : '创建KV对'"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="kvFormRef"
        :model="kvForm"
        :rules="kvFormRules"
        label-width="80px"
      >
        <el-form-item label="Key" prop="key">
          <el-input
            v-model="kvForm.key"
            :disabled="editingKv"
            placeholder="请输入Key"
          />
        </el-form-item>
        
        <el-form-item label="Value" prop="value">
          <el-input
            v-model="kvForm.value"
            type="textarea"
            :rows="4"
            placeholder="请输入Value(可选)"
          />
        </el-form-item>
        
        <el-form-item label="TTL" prop="ttl">
          <el-input-number
            v-model="kvForm.ttl"
            :min="0"
            :max="86400"
            placeholder="过期时间(秒)"
            style="width: 100%"
          />
          <div class="form-help">设置为0表示永不过期</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitting"
            @click="submitForm"
          >
            {{ editingKv ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 高级查询对话框 -->
    <el-dialog
      v-model="queryDialogVisible"
      title="高级查询"
      width="600px"
      @close="resetQueryForm"
    >
      <el-form
        ref="queryFormRef"
        :model="queryForm"
        label-width="120px"
      >
        <el-form-item label="查询类型">
          <el-radio-group v-model="queryForm.type">
            <el-radio label="value">按值查询</el-radio>
            <el-radio label="groupByValue">按值分组统计</el-radio>
            <el-radio label="groupByDate">按日期分组统计</el-radio>
            <el-radio label="groupByDateValue">按日期和值分组</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item 
          v-if="['value', 'groupByValue', 'groupByDateValue'].includes(queryForm.type)"
          label="值模式"
        >
          <el-input
            v-model="queryForm.valuePattern"
            placeholder="输入要查询的值模式，支持通配符%"
          />
          <div class="form-help">例如：user% 查找以user开头的值</div>
        </el-form-item>
        
        <el-form-item 
          v-if="['groupByDate', 'groupByDateValue'].includes(queryForm.type)"
          label="日期范围"
        >
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="queryDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="querying"
            @click="executeQuery"
          >
            查询
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查询结果对话框 -->
    <el-dialog
      v-model="queryResultDialogVisible"
      title="查询结果"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="queryResults.length === 0" class="no-data">
        <el-empty description="暂无查询结果" />
      </div>
      
      <div v-else>
        <!-- 按值查询结果 -->
        <el-table 
          v-if="lastQueryType === 'value'"
          :data="queryResults"
          style="width: 100%"
          max-height="400"
        >
          <el-table-column prop="key" label="Key" width="200" />
          <el-table-column prop="id" label="ID" width="120" />
          <el-table-column prop="value" label="Value" show-overflow-tooltip />
        </el-table>
        
        <!-- 按值分组统计结果 -->
        <el-table 
          v-else-if="lastQueryType === 'groupByValue'"
          :data="queryResults"
          style="width: 100%"
          max-height="400"
        >
          <el-table-column prop="value" label="值" show-overflow-tooltip />
          <el-table-column prop="totalAccessCount" label="总访问次数" width="120" />
          <el-table-column prop="recordCount" label="记录数" width="100" />
          <el-table-column prop="avgAccessCount" label="平均访问次数" width="120">
            <template #default="{ row }">
              {{ row.avgAccessCount?.toFixed(2) || 0 }}
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 按日期分组统计结果 -->
        <el-table 
          v-else-if="lastQueryType === 'groupByDate'"
          :data="queryResults"
          style="width: 100%"
          max-height="400"
        >
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="totalAccessCount" label="总访问次数" width="120" />
          <el-table-column prop="recordCount" label="记录数" width="100" />
          <el-table-column prop="avgAccessCount" label="平均访问次数" width="120">
            <template #default="{ row }">
              {{ row.avgAccessCount?.toFixed(2) || 0 }}
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 按日期和值分组统计结果 -->
        <el-table 
          v-else-if="lastQueryType === 'groupByDateValue'"
          :data="queryResults"
          style="width: 100%"
          max-height="400"
        >
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="value" label="值" show-overflow-tooltip />
          <el-table-column prop="totalAccessCount" label="总访问次数" width="120" />
          <el-table-column prop="recordCount" label="记录数" width="100" />
        </el-table>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="queryResultDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="exportQueryResults">导出结果</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入KV store和系统store
import { useKvStore, useSystemStore } from '../../store/pinia_stores.js'

// 使用stores
const kvStore = useKvStore()
const systemStore = useSystemStore()

// 响应式数据
const tableLoading = ref(false)
const searchTerm = ref('')
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框相关
const dialogVisible = ref(false)
const editingKv = ref(null)
const submitting = ref(false)
const kvFormRef = ref()

// 表单数据
const kvForm = ref({
  key: '',
  value: '',
  ttl: 0
})

// 高级查询相关
const queryDialogVisible = ref(false)
const queryResultDialogVisible = ref(false)
const querying = ref(false)
const queryFormRef = ref()
const queryResults = ref([])
const lastQueryType = ref('')

const queryForm = ref({
  type: 'value',
  valuePattern: '',
  dateRange: null
})

// 表单验证规则
const kvFormRules = {
  key: [
    { required: true, message: '请输入Key', trigger: 'blur' },
    { min: 1, max: 255, message: '长度在1到255个字符', trigger: 'blur' }
  ]
}

// 计算属性
const filteredKvPairs = computed(() => {
  return kvStore.filteredKvPairs
})

const kvPairCount = computed(() => {
  return kvStore.kvPairs.size
})

const filterOptions = ref({
  sortBy: 'key',
  sortOrder: 'asc',
  showOnlyExisted: false
})

// 方法
const handleSearch = (value) => {
  kvStore.setSearchTerm(value)
  currentPage.value = 1
}

const handleSortChange = () => {
  currentPage.value = 1
}

const handleFilterChange = () => {
  currentPage.value = 1
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const showCreateDialog = () => {
  editingKv.value = null
  dialogVisible.value = true
}

const editKv = (row) => {
  editingKv.value = row
  kvForm.value = {
    key: row.key,
    value: row.value || '',
    ttl: row.ttl || 0
  }
  dialogVisible.value = true
}

const deleteKv = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除Key "${row.key}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await kvStore.deleteKv(row.key)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

const submitForm = async () => {
  if (!kvFormRef.value) return
  
  try {
    await kvFormRef.value.validate()
    submitting.value = true
    
    if (editingKv.value) {
      // 更新操作
      await kvStore.updateKv(kvForm.value.key, kvForm.value.value)
      ElMessage.success('更新成功')
    } else {
      // 创建操作
      await kvStore.getOrCreateKv(kvForm.value.key, kvForm.value.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    resetForm()
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  kvForm.value = {
    key: '',
    value: '',
    ttl: 0
  }
  editingKv.value = null
  
  nextTick(() => {
    if (kvFormRef.value) {
      kvFormRef.value.clearValidate()
    }
  })
}

const refreshData = async () => {
  tableLoading.value = true
  try {
    // 重新加载热点数据
    await kvStore.loadHotKeys(50)
  } catch (error) {
    ElMessage.error('刷新失败: ' + error.message)
  } finally {
    tableLoading.value = false
  }
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 高级查询方法
const showQueryDialog = () => {
  queryDialogVisible.value = true
}

const resetQueryForm = () => {
  queryForm.value = {
    type: 'value',
    valuePattern: '',
    dateRange: null
  }
  queryResults.value = []
  lastQueryType.value = ''
}

const executeQuery = async () => {
  try {
    querying.value = true
    queryResults.value = []
    lastQueryType.value = queryForm.value.type
    
    let results = []
    
    switch (queryForm.value.type) {
      case 'value':
        if (!queryForm.value.valuePattern) {
          ElMessage.warning('请输入值模式')
          return
        }
        results = await kvStore.searchByValue(queryForm.value.valuePattern)
        break
        
      case 'groupByValue':
        if (!queryForm.value.valuePattern) {
          ElMessage.warning('请输入值模式')
          return
        }
        results = await kvStore.groupByValue(queryForm.value.valuePattern)
        break
        
      case 'groupByDate':
        if (!queryForm.value.dateRange || queryForm.value.dateRange.length !== 2) {
          ElMessage.warning('请选择日期范围')
          return
        }
        results = await kvStore.groupByDate(
          queryForm.value.dateRange[0],
          queryForm.value.dateRange[1]
        )
        break
        
      case 'groupByDateValue':
        if (!queryForm.value.valuePattern) {
          ElMessage.warning('请输入值模式')
          return
        }
        if (!queryForm.value.dateRange || queryForm.value.dateRange.length !== 2) {
          ElMessage.warning('请选择日期范围')
          return
        }
        results = await kvStore.groupByDateAndValue(
          queryForm.value.dateRange[0],
          queryForm.value.dateRange[1],
          queryForm.value.valuePattern
        )
        break
        
      default:
        ElMessage.error('未知的查询类型')
        return
    }
    
    queryResults.value = results || []
    queryDialogVisible.value = false
    queryResultDialogVisible.value = true
    
    ElMessage.success(`查询完成，共找到 ${queryResults.value.length} 条结果`)
    
  } catch (error) {
    ElMessage.error('查询失败: ' + error.message)
  } finally {
    querying.value = false
  }
}

const exportQueryResults = () => {
  if (queryResults.value.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }
  
  try {
    const csvContent = convertToCSV(queryResults.value, lastQueryType.value)
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `query_results_${new Date().getTime()}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败: ' + error.message)
  }
}

const convertToCSV = (data, queryType) => {
  if (data.length === 0) return ''
  
  let headers = []
  let rows = []
  
  switch (queryType) {
    case 'value':
      headers = ['Key', 'ID', 'Value']
      rows = data.map(item => [item.key, item.id, item.value])
      break
      
    case 'groupByValue':
      headers = ['值', '总访问次数', '记录数', '平均访问次数']
      rows = data.map(item => [
        item.value,
        item.totalAccessCount,
        item.recordCount,
        item.avgAccessCount?.toFixed(2) || 0
      ])
      break
      
    case 'groupByDate':
      headers = ['日期', '总访问次数', '记录数', '平均访问次数']
      rows = data.map(item => [
        item.date,
        item.totalAccessCount,
        item.recordCount,
        item.avgAccessCount?.toFixed(2) || 0
      ])
      break
      
    case 'groupByDateValue':
      headers = ['日期', '值', '总访问次数', '记录数']
      rows = data.map(item => [
        item.date,
        item.value,
        item.totalAccessCount,
        item.recordCount
      ])
      break
      
    default:
      return ''
  }
  
  const csvRows = [headers.join(',')]
  rows.forEach(row => {
    csvRows.push(row.map(field => `"${field}"`).join(','))
  })
  
  return csvRows.join('\n')
}

// 生命周期
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.kv-manager {
  padding: 0;
}

.toolbar-card {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.form-help {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>